import React, { useState, useEffect } from 'react';
import { Button, Input, Card, message, Spin } from 'antd';
import { SendOutlined } from '@ant-design/icons';
import { askWenxin } from '@/services/wenxin';
import { createPortal } from 'react-dom';

interface WenxinAssistantProps {
  teachingContent?: string;
}

const WenxinAssistant: React.FC<WenxinAssistantProps> = ({ teachingContent = '' }) => {
  const [question, setQuestion] = useState('');
  const [answer, setAnswer] = useState('');
  const [loading, setLoading] = useState(false);
  const [collapsed, setCollapsed] = useState(false);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    return () => setMounted(false);
  }, []);

  const handleAsk = async () => {
    if (!question.trim()) {
      message.warning('请输入问题');
      return;
    }

    setLoading(true);
    try {
      const response = await askWenxin(question, teachingContent);
      setAnswer(response.result);
    } catch (error) {
      message.error('获取回答失败，请稍后重试');
      console.error('Error:', error);
    } finally {
      setLoading(false);
    }
  };

  const content = (
    <div className={`wenxin-assistant-container ${collapsed ? 'collapsed' : ''}`}>
      <Card 
        title={
          <div onClick={() => setCollapsed(!collapsed)}>
            智能学习助手
          </div>
        }
      >
        <Input.TextArea
          value={question}
          onChange={(e) => setQuestion(e.target.value)}
          placeholder="请输入你的问题..."
          autoSize={{ minRows: 2, maxRows: 4 }}
        />
        <Button
          type="primary"
          icon={<SendOutlined />}
          onClick={handleAsk}
          loading={loading}
          block
        >
          提问
        </Button>
        
        {loading ? (
          <div className="loading-container">
            <Spin tip="思考中..." />
          </div>
        ) : answer ? (
          <Card size="small" className="answer-card">
            <div className="answer-content">{answer}</div>
          </Card>
        ) : null}
      </Card>
    </div>
  );

  if (!mounted) return null;

  return createPortal(content, document.getElementById('wenxin-assistant-root') || document.body);
};

export default WenxinAssistant; 